package com.flyfox.modules.hr.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Random;

import com.flyfox.jfinal.base.BaseController;
import com.flyfox.jfinal.component.db.SQLUtils;
import com.flyfox.jfinal.template.CRUDFactory;
import com.flyfox.modules.hr.form.SalaryForm;
import com.flyfox.modules.hr.form.SalaryUtils;
import com.flyfox.modules.hr.model.Salary;
import com.flyfox.modules.hr.model.SalaryItem;
import com.flyfox.modules.hr.model.SalaryItemCache;
import com.flyfox.modules.hr.model.SalaryItemCacheObj;
import com.flyfox.util.DateUtils;
import com.flyfox.util.StrUtils;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

public class SalaryController extends BaseController {

	private static final String path = "/pages/salary/";
	Class<Salary> cls = Salary.class;
	private Salary dao = Salary.dao;

	@Override
	public void render(String view) {
		// 省点事
		setAttr("crud", CRUDFactory.instance().get(cls));
		super.render(view);
	}

	public void list() {
		SalaryForm form = getModel(SalaryForm.class, "attr");

		if (StrUtils.isEmpty(form.getSalary_month())) {
			form.setSalary_month(DateUtils.getNow("yyyyMM"));
		}

		SQLUtils sql = new SQLUtils(" from tb_hr_personal p " //
				+ " left join (select * from tb_hr_salary " //
				+ " where salary_month = '" + form.getSalary_month() + "') s ON p.id = s.p_id " //
				+ " left join tb_hr_organizations o on o.id = p.org_id " //
				+ " where 1=1 ");

		if (form.getOrg_id() > 0) {
			sql.whereEquals("p.org_id", form.getOrg_id());
		}

		if (StrUtils.isNotEmpty(form.getP_name())) {
			sql.whereLike("p.p_name", form.getP_name());
		}

		// TODO 暂时只支持一个帐套(通用帐套)，之后可以通过选择设置。
		if (form.getItem_type() <= 0) {
			form.setItem_type(301);
		}
		setAttr("sitem", SalaryItemCache.getCacheObj(form.getItem_type()));

		Page<Salary> page = dao.paginate(getPaginator(), "SELECT p.p_name,p.org_id,o.org_name,s.* ", sql.toString()
				.toString());
		// 下拉框
		setAttr("page", page);
		setAttr("attr", form);
		render(path + "list.bee");

	}

	static String COMMA = ",";
	static String LINE_BREAK = "\r\n";

	public void exportData() {
		SalaryForm form = getModel(SalaryForm.class, "attr");
		SQLUtils sql = new SQLUtils("select p.id as per_id,p.p_name,p.org_id,o.org_name,s.* from tb_hr_personal p " //
				+ " left join (select * from tb_hr_salary " //
				+ " where salary_month = '" + form.getSalary_month() + "') s ON p.id = s.p_id " //
				+ " left join tb_hr_organizations o on o.id = p.org_id " //
				+ " where 1=1 ");
		List<Salary> list = dao.find(sql.toString());
		StringBuffer sb = new StringBuffer();

		SalaryItemCacheObj obj = SalaryItemCache.getCacheObj(form.getItem_type());
		sb.append("序号").append(COMMA) //
				.append("编号").append(COMMA) //
				.append("生成").append(COMMA) //
				.append("姓名").append(COMMA) //
				.append("组织机构").append(COMMA);
		for (Integer key : obj.getItemMap().keySet()) {
			SalaryItem item = obj.getItemMap().get(key);
			sb.append(item.getStr("item_short_name")).append(COMMA);
		}
		sb.append(LINE_BREAK);

		int i = 1;
		for (Salary salary : list) {
			sb.append(i++).append(COMMA);
			sb.append(SalaryUtils.genCode(salary)).append(COMMA);
			sb.append(salary.getInt("id") == null ? "未生成" : "已生成").append(COMMA);
			sb.append(salary.getStr("p_name")).append(COMMA);
			sb.append(salary.getStr("org_name")).append(COMMA);
			for (Integer key : obj.getItemMap().keySet()) {
				String tmpV = salary.getStr("v" + key);
				if (StrUtils.isEmpty(tmpV)) {
					tmpV = obj.getItemMap().get(key).getInt("is_plus") == 3 ? "" : "0";
				}
				sb.append(tmpV).append(COMMA);
			}
			sb.append(LINE_BREAK);
		}

		String path = PathKit.getWebRootPath() + File.separator + "download" + File.separator //
				+ "模板" + DateUtils.getNow("yyyyMMdd") + new Random().nextInt(9999) + ".csv";

		File file = new File(path);
		OutputStreamWriter out = null;
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			OutputStream fout = new FileOutputStream(file);
			out = new OutputStreamWriter(fout, "GBK");
			out.write(sb.toString());
			out.flush();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		renderFile(file);
	}

	public void importData() {
		String salary_month = getAttr("salary_month");
		UploadFile file = getFile();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file.getFile()));
			String tempString = null;
			StringBuffer sb = new StringBuffer();
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				sb.append(tempString).append(LINE_BREAK);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null)
					reader.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

}